<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :span="24">
            <a-breadcrumb>
              <a-breadcrumb-item href="">
                <a-icon type="home" />
                <span>首页</span>
              </a-breadcrumb-item>
              <a-breadcrumb-item href="">
                <a-icon type="user" />
                <span>采购订单管理</span>
              </a-breadcrumb-item>
              <a-breadcrumb-item href="">
                <span>
                <template v-if="this.id !== ''"> <a-icon type="edit" />采购订单编辑</template>
                  <template v-else> <a-icon type="folder-add" />采购订单添加</template>
                </span>
              </a-breadcrumb-item>
            </a-breadcrumb>
          </a-col>
          <a-col :span="24">&nbsp;</a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-page-search-wrapper">
      <a-form-model :model="formData">
        <a-row :gutter="24">
          <a-col :span="16">
            <a-form-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-button-group>
                <a-button type="primary" @click="goBack"> <a-icon type="left" />返回 </a-button>
                <a-button type="primary"  @click="toSave"> 保存<a-icon type="right" /> </a-button>
              </a-button-group>
            </a-form-item>
          </a-col>
          <a-col :span="8" :style="{ textAlign: 'right' }">
            <a-form-item>
              <a-button-group>
                <a-button type="primary" @click="toAudit">
                  <a-icon type="left" />审批
                </a-button>
                <a-button type="primary" @click="onDeliveryOrder">
                  生成到货单<a-icon type="right" />
                </a-button>
              </a-button-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item style="display: none;width:0px;" :labelCol="labelCol" :wrapperCol="wrapperCol"  label="id">
              <a-input v-model="formData.id" />
            </a-form-model-item>
            <a-form-model-item label="订单编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.orderCode" :disabled="disabledOne" placeholder="请输入订单编号"></a-input>
            </a-form-model-item>
            <a-form-model-item label="订单名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.orderName" placeholder="请输入订单名称"></a-input>
            </a-form-model-item>
            <a-form-model-item label="供货商编号" :labelCol="labelCol" v-on: :wrapperCol="wrapperCol">
              <a-input v-model="formData.supplierCode" readOnly
                       placeholder="请输入供货商编号" @click="onSearchSupplier">
                <a-icon slot="prefix" type="bars"/>
              </a-input>
            </a-form-model-item>
            <a-form-model-item label="供货商名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.supplierName" :disabled="disabledOne" placeholder="请输入供货商名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="合同编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.contractCode"
                       readOnly placeholder="请输入合同编号"  @click="onSearchContract">
                <a-icon slot="prefix" type="bars"/>
              </a-input>
            </a-form-model-item>
            <a-form-model-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.contractName" :disabled="disabledOne" placeholder="请输入合同名称"></a-input>
            </a-form-model-item>
            <a-form-model-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.createBy" :disabled="disabledOne" placeholder="请输入创建人"></a-input>
            </a-form-model-item>
            <a-form-model-item label="创建日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择创建日期" v-model="formData.createTime" showTime
                      :dateFormat="dateFormat" :disabled="disabledOne" style="width: 100%"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="总数量" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.totalNum" :disabled="disabledOne" placeholder="请输入总数量"></a-input>
            </a-form-model-item>
            <a-form-model-item label="总金额" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.totalPrice" :disabled="disabledOne" placeholder="请输入总金额"></a-input>
            </a-form-model-item>
            <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="formData.status" :disabled="disabledOne" placeholder="请输入状态"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
    </div>

    <!-- table区域-begin -->
    <div>

      <a-button class="editable-add-btn" @click="handleAdd">
        添加
      </a-button>
      <a-table ref="table" bordered :data-source="dataSource" :columns="columns">
        <template slot="isQuality" slot-scope="text">
          {{ text ? '是' : '否' }}
        </template>
        <template slot="action" slot-scope="text, record">
          <a @click="() => handleEdit(record)">编辑</a>
          <a-divider type="vertical"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => deleteNow(record)">
            <a href="javascript:;">删除</a>
          </a-popconfirm>
        </template>
      </a-table>

    </div>
    <supplier-list-modal ref="supplierModal" @ok="onSupplierOk"></supplier-list-modal>
    <contract-modal ref="contractModal" @ok="onContractOk"></contract-modal>
    <delivery-order-list-modal ref="deliveryOrderListModal" @ok="onDeliveryOrderOk"></delivery-order-list-modal>
    <mms-wz-purchase-order-details-modal ref="modalForm" @ok="modalFormOk"></mms-wz-purchase-order-details-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@lone/lone-vue/src/utils/mixin'
  import { JEditableTableMixin } from '@lone/lone-vue/src/mixins/JEditableTableMixin'
  import { FormTypes } from '@lone/lone-vue/src/utils/JEditableTableUtil'
  import JEditableTable from '@lone/lone-vue/src/components/jeecg/JEditableTable'
  import JDate from '@lone/lone-vue/src/components/jeecg/JDate'
  import { postAction, putAction, deleteAction, getAction } from '@lone/lone-vue/src/api/manage'
  import SupplierListModal from '../base/form/SupplierListModal'
  import ContractModal from '../base/form/ContractModal'
  import DeliveryOrderListModal from '../base/form/DeliveryOrderListModal'
  import MmsWzPurchaseOrderDetailsModal from './modules/MmsWzPurchaseOrderDetailsModal'
  import Vue from 'vue'

  export default {
    name: 'MmsWzPurchaseOrderDetailsList',
    mixins:[JEditableTableMixin, mixinDevice],
    components: {
      DeliveryOrderListModal,
      JDate,
      JEditableTable,
      SupplierListModal,
      ContractModal,
      MmsWzPurchaseOrderDetailsModal
    },
    props:{
      //判断是编辑还是新增
      status:{
        type:String,
        required:false
      },
      //判断是编辑Id
      id:{
        type:String,
        required:false
      },
    },
    watch:{
      status: {
        handler(newVal, oldVal) {
          this.loadFormData()
        },
        immediate: true
      }
    },
    data () {
      return {
        description: 'mms_wz_purchase_order_details管理页面',
        top: 10,
        dateFormat: 'YYYY-MM-DD HH:mm:ss',
        // 表头
        disabledAll: false,
        disabledOne: false,
        editingKey: '',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title: '物资编码',
            dataIndex: 'materialCode'
          },
          {
            title: '物资名称',
            dataIndex: 'materialName'
          },
          {
            title: '规格',
            dataIndex: 'specs'
          },
          {
            title: '型号',
            dataIndex: 'model'
          },
          {
            title: '计量单位',
            dataIndex: 'unit'
          },
          {
            title: '订单数量',
            dataIndex: 'orderNum'
          },
          {
            title: '已到货数量',
            dataIndex: 'arrivalNum'
          },
          {
            title: '已入库数量',
            dataIndex: 'inNum'
          },
          {
            title: '单价',
            dataIndex: 'price'
          },
          {
            title: '金额',
            dataIndex: 'money'
          },{
            title: '是否需要质检',
            dataIndex: 'isQuality',
            scopedSlots: { customRender: 'isQuality' },
          },
          {
            title: '操作',
            dataIndex: 'id',
            scopedSlots: { customRender: 'action' },
          }
        ],
        dataSource: [],
        formData:{},
        url: {
          list: "/cg/mmsWzPurchaseOrderDetails/list",
          delete: "/cg/mmsWzPurchaseOrderDetails/delete",
          deleteBatch: "/cg/mmsWzPurchaseOrderDetails/deleteBatch",
          exportXlsUrl: "/cg/mmsWzPurchaseOrderDetails/exportXls",
          importExcelUrl: "cg/mmsWzPurchaseOrderDetails/importExcel",
        },
        dictOptions:{},
      }
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      loadFormData() {
        let that = this
        that.formData.createTime = Vue.prototype.$formatDate();
        that.formData.totalNum = 0;
        that.formData.totalPrice = 0;
        that.formData.status = "新建";
        this.dataSource = [];
        getAction('/base/mmsMaterialCode/getUserInfo', {}).then((res) => {
          if (res.success) {
            let result = res.result;
            if(result){
              this.$set(this.formData, 'createBy', result['realname']);
            }
          }
        })
        that.loadMaterialUnit();
        if(this.id !== '@ADD@'){
          let paramsObject = {id: this.id};
          getAction('/cg/mmsWzPurchaseOrder/queryById', paramsObject).then((res) => {
            if (res.success) {
              let result = res.result;
              if (result) {
                for(let p in result) {
                  if(p === 'details'){
                    const records = result[p];
                    for(let r in records){
                      let newData = records[r];
                      newData['money'] = parseInt(newData['orderNum']) * parseFloat(newData['price']);
                      that.formData.totalNum += parseInt(newData['orderNum']);
                      that.formData.totalPrice += parseFloat(newData['money']);
                      this.dataSource.push(newData);
                    }
                  }else{
                    this.$set(this.formData, p, result[p]);
                  }
                }

                /* if(status === 'U'){
                   that.disabledOne = true;
                 }*/
                /*else if(status === 'C'){
                  this.disabledAll = true;
                }*/
              }
            }
          });
        }
        that.disabledOne = true;
      },
      modalFormOk(record) {
        let that = this;
        if (record && record.id) {
          const newData = [...this.dataSource];
          const target = newData.filter(item => item.id === record.id)[0];
          record['money'] = parseInt(target['orderNum']) * parseFloat(target['price']);
          that.formData.totalNum -= parseInt(target['orderNum']);
          that.formData.totalPrice -= parseFloat(target['money']);
          newData[newData.indexOf(target)] = record;
          that.formData.totalNum += parseInt(record['orderNum']);
          that.formData.totalPrice += parseFloat(record['money']);
          record['money'] = parseInt(record['orderNum']) * parseFloat(record['price']);
          this.dataSource = newData;
        }else{
          record['money'] = parseInt(record['orderNum']) * parseFloat(record['price']);
          that.formData.totalNum += parseInt(record['orderNum']);
          that.formData.totalPrice += parseFloat(record['money']);
          record['id'] = '';
          this.dataSource.push(record);
        }
      },
      handleDelete: function (id) {
        if(!this.url.delete){
          this.$message.error("请设置url.delete属性!")
          return
        }
        var that = this;
        deleteAction(that.url.delete, {id: id}).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (that.device == that.LoneDevice_M) {
              that.loadData(1);
            } else {
              that.loadData();
            }

          } else {
            that.$message.warning(res.message);
          }
        });
      },
      handleEdit: function (record, params) {
        this.$refs.modalForm.edit(record, params);
        this.$refs.modalForm.title = "编辑";
        this.$refs.modalForm.disableSubmit = false;
      },
      handleAdd: function (params) {
        this.$refs.modalForm.add(params);
        this.$refs.modalForm.title = "新增";
        this.$refs.modalForm.disableSubmit = false;
      },
      onDeliveryOrder (){
        let that = this, orderCode = that.formData.id;
        this.$refs.deliveryOrderListModal.showDeliveryOrderListInfo(orderCode);
      },
      onDeliveryOrderOk (selectionRows, num) {
        let that = this, id = that.formData.id, paramsObject = {id: id, details: selectionRows};
        /*if(selectionRows && selectionRows.length > 0){
          for(let p in selectionRows) {
            let param = {};
            param['code'] = selectionRows[p].materialCode;
            param['currentArrivalNum'] = selectionRows[p].currentArrivalNum;
            paramsObject['details'].push(param);
          }
        }*/
        putAction('/cg/mmsWzPurchaseOrder/arrived', paramsObject).then((res) => {
          if (res.success) {
            that.redirect(id);
          }
        })
      },
      onSearchSupplier (){
        this.$refs.supplierModal.showSupplierInfo();
      },
      onSupplierOk (selectionRows, num) {
        this.$set(this.formData, "supplierName", selectionRows.name);
        this.$set(this.formData, "supplierCode", selectionRows.code);
      },
      onSearchContract (){
        this.$refs.contractModal.showContractInfo();
      },
      onContractOk (selectionRows, num) {
        this.$set(this.formData, "contractName", selectionRows.contractName);
        this.$set(this.formData, "contractCode", selectionRows.contractCode);
      },
      loadMaterialUnit(){
        let that = this;
        getAction('/base/mmsMaterialUnit/list', {}).then((res) => {
          if (res.success) {
            let result = res.result;
            if (result) {
              const options = [];
              for(let r in result.records){
                options[r] = { title: result.records[r]['name'], value: result.records[r]['code'] };
                if(r == 0){
                  that.columns[4].defaultValue = result.records[r]['code'];
                }
              }
              that.columns[4].options = options
            }
          }
        })
      },
      toAudit(){
        let that = this, id = that.formData.id;
        putAction('/cg/mmsWzPurchaseOrder/audit', {id: id}).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            let result = res.result;
            if (result) {
              that.redirect(id);
            }
          }else {
            that.$message.warning(res.message);
          }
        })
      },
      redirect(id){
        let that = this;
        that.$emit("prevStep");
        that.$emit("nextStep",{id:id,status: ''})
      },
      goBack(){
        this.$emit('prevStep')
      },
      handleSelectRowChange(selectedKeys) {
        this.selectedKeys = selectedKeys;
      },
      toSave(){
          let that = this, paramsObject = {details: this.dataSource}, id = that.formData.id;
          for(let param in this.formData){
            this.$set(paramsObject, param, this.formData[param]);
          }
          let action = postAction, url = 'cg/mmsWzPurchaseOrder/add';
          if(paramsObject.hasOwnProperty('id') && paramsObject['id']){
            url = 'cg/mmsWzPurchaseOrder/edit';
            action = putAction;
          }
          action(url, paramsObject).then((res) => {
            if (res.success) {
              this.$message.success(res.message);
              // this.$emit('ok');
              let result = res.result;
              if (result) {
                that.redirect(result['id'])
              }
            } else {
              this.$message.warning(res.message);
              that.redirect(id);
            }
          }).finally(() => {
          })
      },
      deleteNow(record){
        let that = this;
        this.dataSource.splice(this.dataSource.indexOf(record),1);
        that.formData.totalNum -= parseInt(record['orderNum']);
        that.formData.totalPrice -= parseFloat(record['money']);
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';

  .editable-cell:hover .editable-cell-icon {
    display: inline-block;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
</style>